#include "stdafx.h"
#include "Application.h"
#include "../Core/DateTime.h"
#include "../Core/Log.h"
#include "../Core/System.h"

Application::Application() : m_Socket(Protocol_Udp), ApplicationName("")
{
	State = ApplicationState_OnlineUnary;
	m_BroadcastAddress.Address = "255.255.255.255";
	m_BroadcastAddress.PortNumber = 22022;
}

void Application::BroadcastHeartBeat()
{
	try
	{
		RawData t_RawData;
		std::string t_HostName = std::string() + HOSTNAME + "." + DOMAINNAME;//System::GetEnv("HOSTNAME");
		t_RawData.FromString(t_HostName);
		t_RawData.WriteChar(0);
		t_RawData.SetWriteIterator(1024);
		t_RawData.WriteChar(ApplicationId);
		t_RawData.WriteChar(0);
		if(State==ApplicationState_Offline)
		{
			t_RawData.WriteChar(0);
		}
		else
		{
			t_RawData.WriteChar(1);
		}
		if(State==ApplicationState_OnlinePrimary)
		{
			t_RawData.WriteChar(1);
		}
		else if(State==ApplicationState_OnlineStandby)
		{
			t_RawData.WriteChar(2);
		}
		else if (State==ApplicationState_OnlineUnary)
		{
			t_RawData.WriteChar(4);
		}
		else
		{
			t_RawData.WriteChar(0);
		}
		t_RawData.WriteChar(1);
		t_RawData.WriteChar(1);
		DateTime t_DateTime;
		t_RawData.WriteLong(t_DateTime.GetTotalSeconds());
		t_RawData.WriteLong(0);
		m_Socket.SendTo(t_RawData, m_BroadcastAddress);
	}
	catch(...)
	{
		Log::GetSingleton().Write(LogLevel_Error, "Error sending heart beat");
	}
}

void Application::SendMessageToAttnWindow(InternetAddress pDestination , ApplicationMessageLevels pLevel , std::string pMessage) {
    RawData t_RawData;

	t_RawData.WriteChar(1);
	DateTime t_Now;
	t_RawData.WriteLong(t_Now.GetTotalSeconds());
	t_RawData.WriteChar(0);
	t_RawData.WriteChar(0);
	t_RawData.WriteChar(0);

    t_RawData.WriteChar((unsigned char) pLevel);
    t_RawData.WriteChar(0);

    t_RawData.WriteChar(ApplicationId);
    t_RawData.WriteChar(0);
    for (unsigned int i = 0 ; i < ApplicationName.length() ; i++) {
        t_RawData.WriteChar(ApplicationName[i]);
    }
    t_RawData.WriteChar(0);

    t_RawData.SetWriteIterator(80);

    pMessage = t_Now.ToString("%H:%M ") + ApplicationName + " " + pMessage;
    for(int i=0; i<(int)pMessage.length(); i++)
	{
		t_RawData.WriteChar(pMessage[i]);
	}

    m_Socket.SendTo(t_RawData , pDestination);
}

void Application::ExecuteByInterval()
{
	BroadcastHeartBeat();
}
